<template>
  <div style="background-image: url(/src/assets/img/backgwc.jpg)" >
    <div class="header-container" style="background-color: pink;">
      <div class="left1">
        <img src="../assets/img/logo.webp" class="icon" />
        <span><h1>🛒购物车🚗</h1></span>
      </div>
      <div class="right1">
        <span @click="back">返回主页</span>
        <span @click="Tochat">聊天</span>
        <span @click="Toreport">举报</span>
        <span @click="Touesr">个人中心</span>
      </div>
    </div>
    <div class="goods-container" v-if="!showDialog" style="min-height: 120vh; background-image: url(/src/assets/img/backgoin.jpg);opacity: 0.9;">
      <div class="title">购物车商品</div>
      <div class="goods" v-for="(item, index) in items" :key="index">
        <div class="left">
          <el-checkbox v-model="item.checked" size="large" />
          <img :src="item.image" alt="图片" />
          <div class="name">{{ item.name }}</div>
        </div>
        <div class="right">
          <div class="quantity">库存{{ item.quantity }}件</div>
          <div class="price">¥{{ item.price }}</div>
          <div class="about">
            <el-button type="primary" @click="deleteCart(index)">移除购物车</el-button>
            <div class="number">
              <el-button type="primary" @click="reduceCount(index)">-</el-button>
              <div class="num">{{ item.count }}</div>
              <el-button type="primary" @click="addCount(index)">+</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="quanxuan">
          <input type="checkbox" class="check-input" v-model="selectAll" @change="toggleSelectAll" />
          <label class="check-label">全选</label>
        </div>
        <div>
          <span class="total">合计:</span>
          <span class="price">¥{{ totalPrice }}</span>
        </div>
        <div class="tijiao">
          <el-button type="primary" @click="makeOrder">生成订单</el-button>
          <el-button type="primary" @click="fakeBuy">取消购买</el-button>
        </div>
      </div>
    </div>
    <div class="dialog-container" v-if="showDialog">
      <div class="dialog-title">订单信息</div>
      <div class="dialog-content">
        <div class="order-id">订单编号:{{ order.id }}</div>
        <div class="order-list">订单物品:</div>
        <ul>
          <li v-for="(item, index) in order.products" :key="index" class="order-item">
            <img :src="item.image" alt="图片" class="order-item-image" />
            <span>{{ item.name }} x {{ item.count }}</span>
          </li>
        </ul>
        <div class="order-price">订单总价格:¥{{ order.totalAmount }}</div>
      </div>
      <div class="dialog-button">
        <el-button type="primary" @click="toSuccessBuy">确认购买</el-button>
        <el-button type="primary" @click="backback">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { globalState } from '../global'; // 引用 globalState

export default {
  data() {
    return {
      items: [],
      selectAll: false,
      updatedItems: [],
      showDialog: false,
      count: 0,
      order: {
        id: null,
        totalAmount: 0,
        products: []
      }
    };
  },
  mounted() {
    this.fetchItems();
  },
  methods: {
    toggleAll() {
      this.items.forEach(item => (item.checked = !this.isAllChecked));
    },
    calculateTotal() {
      let total = 0;
      this.items.forEach(item => {
        if (item.checked) {
          total += item.price * item.count;
        } else {
          total += 0;
        }
      });
      return total;
    },
    toggleSelectAll() {
      this.items.forEach(item => (item.checked = this.selectAll));
    },
    makeOrder() {
      const selectedItems = this.items.filter(item => item.checked);
      if (selectedItems.length === 0) {
        this.$message.error('购物车中没有选中的商品，无法生成订单');
        return;
      }
      const orderData = {
        status: '未支付',
        totalAmount: this.totalPrice,
        username: this.$globalState.username, // 获取当前用户的用户名
        products: selectedItems
      };
      console.log(this.$globalState.username); // 检查是否正确获取到用户名
      axios
        .post('http://localhost:8080/api/orders', orderData)
        .then(response => {
          this.order = response.data;
          // 更新物品库存
          const updatedItems = this.items.map(item => ({
            id: item.id,
            quantity: item.quantity - item.count
          }));
          axios.put('http://localhost:8080/api/products/test', updatedItems);
          axios.post('http://localhost:8080/deleteCart');
          this.fetchItems();
          this.showDialog = true;
        })
        .catch(error => {
          console.log(error);
        });
    },
    backback() {
      this.fetchItems(); // 更新购物车
      this.showDialog = false;
    },
    async deleteCart(index) {
      const id = this.items[index].id;
      axios
        .delete(`http://localhost:8080/${id}`)
        .then(response => {
          this.fetchItems();
        })
        .catch(error => {
          console.log(error);
        });
    },
    async fetchItems() {
      try {
        const response = await axios.get('http://localhost:8080/cartitem');
        this.items = response.data;
      } catch (error) {
        console.log(error);
      }
    },
    toSuccessBuy() {
      const currentTime = new Date().toISOString();
      const data = {
        date: currentTime,
        text: this.formattedOrder
      };
      axios.post('http://localhost:8080/api/log/logmes', data);
      this.$router.push({
        path: '/successBuy',
        query: { orderId: Number(this.order.id) }
      });
    },

    fakeBuy() {
      this.$router.push('/mainpage');
    },
    addCount(index) {
      if (this.items[index].count < this.items[index].quantity) {
        this.items[index].count++;
      }
    },
    reduceCount(index) {
      if (this.items[index].count > 0) {
        this.items[index].count--;
      }
    },
    Tochat() {
      this.$router.push('/chat');
    },
    Touesr() {
      this.$router.push('/userPage');
    },
    back() {
      this.$router.push('/mainpage');
    },
    Toreport() {
      this.$router.push('/report');
    }
  },
  computed: {
    isAllChecked() {
      return this.items.every(item => item.checked);
    },
    totalPrice() {
      return this.calculateTotal();
    },
    formattedOrder() {
      let text = '用户' + globalState.username + '购买了商品：\n';
      this.order.products.forEach(item => {
        text += `${item.name} x ${item.count}, `;
      });
      // 去掉末尾的逗号
      text = text.slice(0, -2);
      return text;
    }
  }
};
</script>

<style lang="less" scoped>
.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  padding: 0 20px;
  background-color: #ffffff; /* 调整背景色 */
  color: rgb(23, 98, 236);
}

.left1 {
  display: flex;
  align-items: center;
  align-content: center;
}

.right1 {
  display: flex;
  gap: 20px;
}

.right1 span {
  cursor: pointer;
  transition: color 0.3s;
}

.right1 span:hover {
  color: red;
}

.icon {
  width: 200px;
  height: 150px;
}

.goods-container {
  width: 80%;
  margin: 30px auto;
  background-color: rgb(12, 202, 219);
  border: 1px solid black;
}

.title {
  height: 40px;
  line-height: 40px;
  font-size: 24px;
  text-align: center;
  color: black;
  background-color: whitesmoke;
}

.goods {
  display: flex;
  justify-content: space-between;
  background-color: rgb(238, 232, 232);
  border: 1px solid black;
  margin-bottom: 10px;
}

.left {
  display: flex;
  align-items: center;
  color: black;
}

.left img {
  width: 100px;
  height: 100px;
  border: 1px solid red;
}

.right {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.about {
  display: flex;
  align-items: center;
  gap: 20px;
}

.number {
  display: flex;
  align-items: center;
}

.num {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: whitesmoke;
  border: 1px solid black;
  padding: 10px 20px;
}

.quanxuan {
  display: flex;
  align-items: center;
}

.check-input {
  margin-right: 5px;
}

.check-label {
  font-size: 18px;
  color: black;
}

.tijiao {
  display: flex;
  gap: 10px;
}

.total {
  color: black;
}

.price {
  color: red;
}

.dialog-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  max-width: 90%;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background-color: #fff;
  overflow: hidden;
}

.dialog-title {
  font-size: 24px;
  text-align: center;
  background-color: #f0c040;
  color: #fff;
  padding: 20px;
  font-weight: bold;
}

.order-id,
.order-list,
.order-price {
  margin: 20px;
  font-size: 18px;
}

.order-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
  font-size: 16px;
}

.order-item img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  border-radius: 5px;
}

.dialog-content {
  padding: 20px;
  border-top: 1px solid #eee;
}

.dialog-button {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.el-button {
  font-size: 16px;
  padding: 10px 20px;
}
</style>
